<?php
require_once('../includes/settings.php');
require_once('../includes/functions.php');
require_once('../includes/repository.php');
require_once('../includes/sql.php');

deny_get_request();
deny_anonymous();
parameters_check($_REQUEST['action']);

$action = strtolower($_REQUEST['action']);
$user_id = user_val('id');

function is_collected_by_otherone($sentence_id,$user_id){
	$sql = "SELECT count(id) count FROM voca.voca_user_sentences WHERE sentence_id=? AND user_id != ?";
	$stmt = Repository::prepare($sql);
	$stmt -> bind_param('ii', $sentence_id,$user_id);
	$stmt -> execute();
	$result = Repository::get_result($stmt);
	return  $result[0]['count']>0;
}

if($action=="save"){
	$word_id=intval($_POST['word_id']);
	$sentence_id='';
	if(isset($_POST['sentence_id'])){
		$sentence_id = intval($_POST['sentence_id']);
	}
	$sentence = trim($_POST['sentence']);
	$translation = trim($_POST['translation']);
	if($sentence=='' || $translation==''){
		_jsonp(FALSE,array("error"=>'Invalid Parameters'));
		exit();
	}
	$sentence = compact_string($sentence);
	$translation = compact_string($translation);
	if($sentence_id==''){
		$sentence_id = Sentence::create($word_id,$sentence,$translation,$user_id);
	}else{
		Sentence::update($sentence_id,$sentence,$translation);
	}
	Repository::commit();
	Repository::close();
	_jsonp(TRUE,array("sentence_id"=>$sentence_id));
	

}elseif ($action=='like') {
	$sentence_id = intval($_POST['sentence_id']);
	$id=Sentence::create_user_sentence($user_id, $sentence_id, FALSE);
	Repository::commit();
	Repository::close();
	_jsonp(TRUE);

}elseif ($action=="dislike") {
	$sentence_id = intval($_POST['sentence_id']);
	Sentence::remove_user_sentence($user_id,$sentence_id);
	Sentence::add_to_blacklist($sentence_id, $user_id);
	Repository::commit();
	Repository::close();
	_jsonp(TRUE);

}elseif($action=="remove"){
	$sentence_id = intval($_POST['sentence_id']);
	if( is_collected_by_otherone($sentence_id, $user_id) ){//移除关联并加入黑名单
		Sentence::remove_user_sentence($user_id, $sentence_id);
		Sentence::add_to_blacklist($sentence_id, $user_id);
		Repository::commit();
		Repository::close();
	}else{
		Sentence::remove($sentence_id);
		Sentence::remove_user_sentence($user_id, $sentence_id);
		Repository::commit();
		Repository::close();
	}
	_jsonp(TRUE);
}

?>